package edu.whu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.whu.demo.domain.Commodity;
import edu.whu.demo.domain.Supplier;
import edu.whu.demo.dao.SupplierDao;
import edu.whu.demo.exception.ProductAdminException;
import edu.whu.demo.service.ISupplierService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yang hengyi
 * @since 2022-10-24
 */
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierDao, Supplier> implements ISupplierService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Supplier addSupplier(@NotNull Supplier supplier) {
        supplier.setId(null);
        if(!save(supplier)){
            throw new RuntimeException("添加失败");
        }
        return supplier;
    }

    public List<Supplier> batchGetSuppliers(List<Long> ids) {
        List<Supplier> suppliers = new ArrayList<>();
        for(long id: ids){
            suppliers.add(getById(id));
        }
        return suppliers;
    }
    @Override
    @Transactional
    public void deleteSupplier(Long id) throws ProductAdminException {
        Optional.ofNullable(getById(id))
                .orElseThrow(()->new ProductAdminException("数据不存在"));

        if(!removeById(id)){
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    public Supplier updateSupplier(@NotNull Supplier supplier) throws ProductAdminException {
        Optional.ofNullable(getById(supplier.getId()))
                .orElseThrow(()->new ProductAdminException("供应商不存在"));

        if(!updateById(supplier)){
            throw new ProductAdminException("更新失败");
        }
        return supplier;
    }

    @Override
    public Page<Supplier> findSuppliers(String name, String tel, Page page) {
        QueryWrapper<Supplier> qw = new QueryWrapper<>();
        qw.like(null != name, "name", name).eq(null != tel, "tel", tel);
        return  getBaseMapper().selectPage(page, qw);
    }


}
